<template>
  <v-row id='process_container' justify="center">
    <v-dialog
      v-resize="onResize"
      v-model="dialog_"
      fullscreen
      hide-overlay
      transition="dialog-bottom-transition"
    >
      <v-card>
        <v-toolbar
          dark
          flat
          color="primary"
        >
          <v-btn
            icon
            dark
            @click="dialog_ = false"
          >
            <v-icon>mdi-close</v-icon>
          </v-btn>
          <v-toolbar-title>图像处理 - {{img.name}}</v-toolbar-title>
          <v-spacer></v-spacer>
          <v-toolbar-items>
            <v-btn
              dark
              text
              :disabled='!isProcessed'
              @click="showSaveDialog"
            >
              保存至我的相册
            </v-btn>
            <v-btn
              dark
              text
              @click="downloadImg"
            >
              下载图片
            </v-btn>
          </v-toolbar-items>
        </v-toolbar>
       <v-row
         class='my-0'
         :style="processStyle"
       >
         <v-col style='height: 100%' :cols='isReadOnly?12:8'>
             <v-img
               height='100%'
               contain
               :src='previewUrl'
             >
               <template v-slot:placeholder>
                 <v-row
                   class="fill-height ma-0"
                   align="center"
                   justify="center"
                 >
                   <v-progress-circular
                     indeterminate
                     color="grey lighten-5"
                   ></v-progress-circular>
                 </v-row>
               </template>
             </v-img>
         </v-col>
         <v-col
           v-if='!isReadOnly'
           cols='4'
           style='height: 100%;overflow-y: scroll;'
           class='pt-4 text-center justify-center' >
           <v-card-title>
             <v-icon>mdi-gesture</v-icon>操作
             <v-spacer></v-spacer>
             <v-btn icon @click='refreshProcess'><v-icon>mdi-refresh</v-icon></v-btn>
           </v-card-title>
             <v-expansion-panels  multiple>
               <v-expansion-panel>
                 <v-expansion-panel-header>旋转</v-expansion-panel-header>
                 <v-expansion-panel-content >
                   <v-btn outlined color='secondary' @click='imgRotate(-90)'><v-icon>mdi-rotate-left</v-icon></v-btn>
                   <v-btn outlined color='secondary' @click='imgRotate(90)'><v-icon>mdi-rotate-right</v-icon></v-btn>
                   <v-slider
                     v-model="rotateArc"
                     label="值"
                     min='0'
                     max='360'
                     color='secondary'
                     thumb-color="primary"
                     thumb-label="always"
                     @end='imgRotate'
                   ></v-slider>
                 </v-expansion-panel-content>
               </v-expansion-panel>
               <v-expansion-panel>
                 <v-expansion-panel-header>效果</v-expansion-panel-header>
                 <v-expansion-panel-content>
                   <v-switch
                     v-model="sharpenEnable"
                     label="开启锐化"
                     color='secondary'
                     @change='resetShape'
                   ></v-switch>
                   <v-slider
                     v-model="sharpenValue"
                     label="值"
                     min='50'
                     max='399'
                     :disabled='!sharpenEnable'
                     color='secondary'
                     thumb-color="primary"
                     thumb-label="always"
                     @end='sharpOnEnd'
                   ></v-slider>
                   <v-divider/>
                   <v-switch
                     v-model="blurEnable"
                     label="开启模糊"
                     color='secondary'
                     @change='resetBlur'
                   ></v-switch>
                   <v-slider
                     v-model="blurValue"
                     label="标准差"
                     min='1'
                     max='50'
                     :disabled='!blurEnable'
                     color='secondary'
                     thumb-color="primary"
                     thumb-label="always"
                     @end='blurOnEnd'
                   ></v-slider>
                   <v-slider
                     v-model="blurRadiusValue"
                     label="半径"
                     min='1'
                     max='50'
                     :disabled='!blurEnable'
                     color='secondary'
                     thumb-color="primary"
                     thumb-label="always"
                     @end='blurOnEnd'
                   ></v-slider>
                 </v-expansion-panel-content>
               </v-expansion-panel>
               <v-expansion-panel>
                 <v-expansion-panel-header>大小</v-expansion-panel-header>
                 <v-expansion-panel-content>
                   <v-switch
                     v-model="circleEnable"
                     label="开启圆角"
                     color='secondary'
                     @change='resetCircle'
                   ></v-switch>
                   <v-slider
                     v-model="circleValue"
                     label="半径"
                     min='1'
                     max='200'
                     :disabled='!circleEnable'
                     color='secondary'
                     thumb-color="primary"
                     thumb-label="always"
                     @end='circleOnEnd'
                   ></v-slider>
                   <v-divider/>
                   <v-slider
                     v-model="compressValue"
                     label="图像压缩"
                     min='1'
                     max='100'
                     color='secondary'
                     thumb-color="primary"
                     thumb-label="always"
                     @end='compressOnEnd'
                   ></v-slider>
                 </v-expansion-panel-content>
               </v-expansion-panel>
               <v-expansion-panel>
                 <v-expansion-panel-header>水印</v-expansion-panel-header>
                 <v-expansion-panel-content>
                   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
                 </v-expansion-panel-content>
               </v-expansion-panel>
             </v-expansion-panels>
         </v-col>
       </v-row>
      </v-card>
    </v-dialog>
    <v-dialog
      v-model="saveProcessDialog"
      transition="dialog-bottom-transition"
      max-width="600px"
    >
      <v-card>
        <v-card-title>
          <span class='text-h5'>输入图片新名字</span>
        </v-card-title>
        <v-divider/>
        <v-card-text>
          <v-row class='mt-3'>
            <v-col cols='4' align-self='center'>
              请输入新图片名:
            </v-col>
            <v-col cols='8'>
              <v-text-field
                dense
                clearable
                :suffix='suffix'
                @change='nameChange'
                v-model='newImgName'
              />
            </v-col>
          </v-row>
          <v-row justify='center' class='pt-3 ' >
            注:新图片名不能与原图片名相同,图片将保存至 <strong>'我的相册'</strong> 根目录
          </v-row>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <progress-button
            :text="true"
            :loading='loading'
            :disabled='saveBtnDisable'
            progressColor="primary"
            color="primary"
            @click="saveImg"
            title="保存">
          </progress-button>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-row>
</template>

<script>
  import progressButton from '@/components/common/ProgressButton'
  import moment from 'moment'
  import imagesApi from '@/api/apiPath/imagesApi'

  export default {
    name: 'ImageProcess',
    components: {
      progressButton
    },
    props: {
      dialog: {
        types: Boolean,
        default: false
      },
      img: {
        type: Object
      },
      isReadOnly: {
        type: Boolean
      },
      tagName: {
        default: ''
      },
      groupName: {
        default: ''
      }
    },
    data() {
      return {
        thumbImg: require('@/assets/logo.png'),
        processHeight: window.innerHeight - 60,
        previewUrl: this.img.url,
        rotateArc: 0,
        sharpenValue: 50,
        sharpenEnable: false,
        compressValue: 100,
        circleValue: 100,
        circleEnable: false,
        blurRadiusValue: 50,
        blurValue: 50,
        blurEnable: false,
        isProcessed: false,
        settingCopy: {},
        saveProcessDialog: false,
        newImgName: '',
        suffix: '',
        loading: false,
        saveBtnDisable: false,

        processGather: {
          rotate: undefined,
          sharpen: undefined,
          quality: undefined,
          'rounded-corners': undefined,
          blur: undefined
        }
      }
    },
    computed: {
      dialog_: {
        get() {
          return this.dialog;
        },
        set(val) {
          this.refreshProcess()
          this.$emit('on-change-dialog', val);
        }
      },
      processStyle: {
        get() {
          return {
            height: this.processHeight + 'px'
          }
        }
      },
      handleProcessStr: {
        get() {
          if (this.isProcessed) {
            const temp = this.previewUrl
            return temp.split('?x-oss-process=')[1]
          }
          return ''
        }
      },
      newFullImgName: {
        get() {
          return this.newImgName + this.suffix
        }
      }
    },
    watch: {
      img: {
        handler() {
          this.previewUrl = this.img.url
          this.onResize()
        },
        deep: true
      },
      processGather: {
        handler(val) {
          let processFlag = false
          this.previewUrl = this.img.url + '?x-oss-process=image'
          Object.keys(val).forEach((key) => {
           if (val[key]) {
             processFlag = true
             this.isProcessed = true
             this.previewUrl += `/${key},${val[key]}`
           }
         })
          if (!this.isProcessed || !processFlag) {
            this.previewUrl = this.img.url
          }
          console.log(this.previewUrl)
        },
        deep: true
      }
    },
    created() {
      this.settingCopy = {
        rotateArc: this.rotateArc,
        sharpenValue: this.sharpenValue,
        sharpenEnable: this.sharpenEnable,
        compressValue: this.compressValue,
        circleValue: this.circleValue,
        circleEnable: this.circleEnable,
        blurRadiusValue: this.blurRadiusValue,
        blurValue: this.blurValue,
        blurEnable: this.blurEnable,
        isProcessed: false
      }
    },
    beforeUpdate() {

    },
    methods: {
      // 重置操作
      refreshProcess() {
        this.previewUrl = this.img.url
        Object.keys(this.settingCopy).forEach((key) => {
          this[key] = this.settingCopy[key]
        })
        Object.keys(this.processGather).forEach((key) => {
          this.processGather[key] = undefined
        })
      },
      onResize() {
        this.processHeight = window.innerHeight - 64
      },
      imgRotate(val) {
        if (val === 90 || val === -90) {
          if (this.rotateArc + val < 0 && val < 0) {
            this.rotateArc = 360 + this.rotateArc + val
          } else {
            this.rotateArc = (this.rotateArc + val) % 360
          }
        }
        this.processGather.rotate = this.rotateArc === 0 ? undefined : this.rotateArc
      },
      resetShape(val) {
        if (val) {
          this.processGather.sharpen = this.sharpenValue
        } else {
          this.processGather.sharpen = undefined
        }
      },
      sharpOnEnd(val) {
        this.processGather.sharpen = val
      },
      compressOnEnd(val) {
        this.processGather.quality = `q_${val}`
      },
      resetCircle(val) {
        if (val) {
          this.processGather['rounded-corners'] = `r_${this.circleValue}`
        } else {
          this.processGather['rounded-corners'] = undefined
        }
      },
      circleOnEnd(val) {
        this.processGather['rounded-corners'] = `r_${val}`
      },
      resetBlur(val) {
        if (val) {
          this.processGather.blur = `r_${this.blurRadiusValue},s_${this.blurValue}`
        } else {
          this.processGather.blur = undefined
        }
      },
      blurOnEnd(val) {
        this.processGather.blur = `r_${this.blurRadiusValue},s_${this.blurValue}`
      },
      showSaveDialog() {
        const temp = this.img.name.split('.')
        this.newImgName = temp[0] + moment().format('YYYYMMDDhhmm')
        this.suffix = '.' + temp[1]
        this.saveProcessDialog = true
      },
      nameChange(val) {
        this.saveBtnDisable = val === '' || val === this.newImgName;
      },
      async saveImg() {
        this.loading = true
        try {
          const data = {
            fileName: this.img.name,
            newName: this.newFullImgName,
            processStr: this.handleProcessStr
          }
          if (this.tagName) {
            data.tagName = this.tagName
          } else if (this.groupName) {
            data.groupName = this.groupName
          }
          const { data: result } = await imagesApi.processImage(data)
          this.loading = false
          this.$toast.success(result)
          setTimeout(() => {
            this.$emit('freshList')
            this.dialog_ = false
          },200)
        } catch (e) {
          this.loading = false
          this.$toast.error(e)
        }
        this.saveProcessDialog = false
      },
      downloadImg() {
        window.open(this.previewUrl)
        this.dialog_ = false
      }
    }
  }
</script>

<style scoped>
</style>
